<?php

namespace Biz\service\Store;


use Biz\model\store\StoreAccount as mAccount;
use Biz\model\store\StoreAuth as mAuth;
use Biz\model\store\StoreBasic;
use Biz\model\store\StoreBasic as mBasic;
use Biz\model\store\StoreMsg;
use Biz\model\store\StoreOperator as mOperator;
use Biz\model\store\StoreUserConsult;
use Biz\service\admin\StoreCheck as sCheck;
use Biz\service\wiki\Wiki;
use Doraemon\service\User;
use Doraemon\tools\ImgUrl;

/**
 * 门店服务平台专用
 * Class StoreBusinessService
 * @package Biz\service\Store
 */
class StoreBusinessService
{
    /**
     * 获取基础信息（门店服务平台专用）
     * @param int store_id
     * @return array $result
     */
    public static function getBasicInfoByStoreId($store_id = 0)
    {
        $result = [];
        $basic_info = mBasic::first(['id' => $store_id]);
        if ($basic_info && is_array($basic_info)) {
            $alias = json_decode($basic_info['alias'], true) ?: [];
            if ($alias && is_array($alias)) {
                $check_info = sCheck::getCheckStatusByAlias($store_id, $alias);
            }
            $result['logo'] = [
                'logo_pic' => $basic_info['logo_pic'],
                'logo_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $basic_info['logo_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE),
            ];
            $result['cover'] = [
                'cover_pic' => $basic_info['cover_pic'],
                'cover_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $basic_info['cover_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE)
            ];
            $result['card_cover'] = [
                'card_cover_pic' => $basic_info['card_cover_pic'],
                'card_cover_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $basic_info['card_cover_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE)
            ];
            $result['name'] = $basic_info['name'];
            $result['alias'] = $check_info ?: [];
            $result['phone'] = $basic_info['phone'];
            $result['open_time'] = json_decode($basic_info['open_time'], true);
            $result['address'] = $basic_info['address'];
            $result['show_address'] = $basic_info['show_address'];
            $result['desc'] = $basic_info['desc'];
            $result['server_trait'] = $basic_info['server_trait'];
            $result['server_area'] = $basic_info['server_area'];
            $result['server_content'] = $basic_info['server_content'];
            $result['city_id'] = $basic_info['city_id'];
            $result['city_name'] = $basic_info['city_name'];
            $result['area_name'] = $basic_info['area_name'];
            $result['area_code'] = $basic_info['area_code'];
        }
        return $result;
    }

    /**
     * 修改basic 信息
     * @param $store_id
     * @param $data
     * @return false
     */
    public static function updateBasicByStoreId($store_id, $data)
    {
        sCheck::updateCheckByStoreId($store_id, $data);
        return mBasic::updateById($store_id, $data);

    }

    /**
     * @param int $store_id
     * @return array
     */
    public static function getOperatorInfoByStoreId($store_id = 0)
    {
        $result = [];

        $account_info = mAccount::getInfoByWhere(['store_id' => $store_id]);
        if ($account_info && is_array($account_info)) {
            $operator_info = mOperator::getInfoByAid($account_info['id']);
            if ($operator_info && $operator_info) {
                $result['phone'] = $operator_info['phone'];
                $result['name'] = $operator_info['name'];
                $result['wx_id'] = $operator_info['wx_id'];
                $result['email'] = $operator_info['email'];
            }
        }
        return $result;
    }

    /**
     * @param int $store_id
     * @return array
     */
    public static function getAuthInfoByStoreId($store_id = 0)
    {
        $result = [];
        $account_info = mAccount::getInfoByWhere(['store_id' => $store_id]);
        if ($account_info && is_array($account_info)) {
            $auth_info = mAuth::getInfoByAid($account_info['id']);
            if ($auth_info && $auth_info) {
                $result['company_name'] = $auth_info['company_name'];
                $result['business_license_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $auth_info['business_license_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE);
                $result['license_period'] = $auth_info['license_period'];
                $result['opening_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $auth_info['opening_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE);
                $result['trademark_regist_pic_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $auth_info['trademark_regist_pic'], ImgUrl::IMAGE_SIZE_SQ_PHONE);
                $result['auth_start_time'] = $account_info['auth_start_time'];
                $result['auth_end_time'] = $account_info['auth_end_time'];

            }
        }
        return $result;
    }


    /**
     * 写入服务平台消息
     * @param int $storeId
     * @param int $msgType
     * @param int $msgSource StoreMsg::MSG_SOURCE_STORE_INFO
     * @param string $msgInfo
     * @param int $objType
     * @param string $objId
     * @return false|int|mixed|string
     */
    public static function writeMsg($storeId = 0, $msgType = StoreMsg::MSG_TYPE_PASS, int $msgSource = 0, $msgInfo = '', $objType = -1, $objId = '')
    {
        return StoreMsg::add([
            "store_id" => $storeId,
            "msg_type" => $msgType,
            "msg_source" => $msgSource,
            "addtime" => date('Y-m-d H:i:s', time()),
            "msg_info" => $msgInfo,
            "obj_type" => $objType,
            "obj_id" => $objId
        ]);
    }

    /**
     * 获取服务平台首页消息
     * @param $storeId
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public static function getMsgs($storeId, $page = 1, $pageSize = 20)
    {
        $msg_list = [];
        $where = [
            'store_id' => $storeId,
            'LIMIT' => [($page - 1) * $pageSize, $pageSize],
            'ORDER' => [
                'addtime' => 'DESC'
            ],
        ];
        $msgs = StoreMsg::getListByWhere($where);
        if ($msgs && is_array($msgs)) {
            foreach ($msgs as $row) {
                $msg_list[] = [
                    "id" => (int)$row['id'],
                    "store_id" => (int)$row['store_id'],
                    "msg_type" => (int)$row['msg_type'],
                    "msg_source" => (int)$row['msg_source'],
                    "msg_info" => $row['msg_info'],
                    "addtime" => date('Y.m.d', strtotime($row['addtime'])),
                    "obj_type" => (int)$row['obj_type'],
                    "obj_id" => $row['obj_id']
                ];
            }
        }
        $count = StoreMsg::getCount(['store_id' => $storeId]);
        $isOver = ($page * $pageSize >= $count) ? 1 : 0;
        return ['list' => array_values($msg_list), 'total' => $count, 'is_over' => $isOver];
    }

    /**
     * 门店服务平台-留资列表
     * @param $where
     * @return array
     */
    public static function getUserConsultList($where)
    {
        $arr = StoreUserConsult::getListByWhere($where);
        unset($where['ORDER']);
        unset($where['LIMIT']);
        $count = StoreUserConsult::getCount($where);
        $list = [];
        if ($arr) {
            $uids = array_column($arr, 'uid');
            $uids = array_unique($uids);
            $userInfos = User::getBatchBasicUserInfo($uids);
            $userInfos = array_column($userInfos, null, 'uid');
//            $wikiIds = array_column($arr, 'wiki_id');
//            $wikiIds = array_unique(array_filter($wikiIds));
//            $wikiList = $wikiIds ? Wiki::getWikiBaseList($wikiIds) : [];
            foreach ($arr as $row) {
                $nick = isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['nick'] : '';
                $title = '';
                switch ($row['source']) {
                    case StoreUserConsult::SOURCE_STORE_HOME:
                        $title = $nick . ' 留下了预约信息，想进一步了解门店更多信息，请尽快联系用户哦～';
                        break;
                    case StoreUserConsult::SOURCE_STORE_ACTIVITY:
                        $title = $nick . ' 领取了门店优惠，并留下了预约信息，请尽快联系用户。';
                        break;
                    case StoreUserConsult::SOURCE_WIKI_DETAIL:
                        //$wikiTitle = ($row['wiki_id'] && isset($wikiList[$row['wiki_id']])) ? $wikiList[$row['wiki_id']]['title'] : '';
                        //$wikiTitle = $wikiTitle ? ('(' . $wikiTitle . ')') : '';
                        $title = $nick  . ' 留下了预约信息，请尽快联系用户。';
                        break;
                }
                $item = [
                    'id' => $row['id'],
                    'uid' => $row['uid'],
                    'nick' => $nick,
                    'source' => StoreUserConsult::SOURCE_MAP[$row['source']],
                    'title' => $title,
                    'city' => $row['city'],
                    'area_name' => $row['area_name'],
                    'area_code' => $row['area_code'],
                    'remark' => empty($row['remark']) ? ($row['consult_status'] == StoreUserConsult::CONSULT_STATUS_TEL ? '已联系': '' ) : $row['remark'] ,
                    'addtime' => date('Y-m-d', strtotime($row['addtime'])),
                    'bind_status' => $row['bind_status'],
                    'virtual_phone' => $row['virtual_phone'],
                    'official_phone' => empty($row['official_phone']) ? '/' : $row['official_phone'],
                ];

                if($row['virtual_expire_time'] == '0000-00-00 00:00:00'){
                    $item['virtual_expire_time'] = '';
                }elseif(time() > strtotime($row['virtual_expire_time'])){
                    $item['virtual_expire_time'] = '已过期';
                }else{
                    $item['virtual_expire_time'] = date('Y.m.d', strtotime($row['virtual_expire_time']));
                }
                $list[] = $item;
            }
        }
        return ['list' => $list, 'total' => $count];
    }

    /**
     * 门店服务平台-更改留资状态
     * @param $consultId
     * @param $consultStatus
     * @return bool
     */
    public static function changeConsultStatus($consultId, $consultStatus)
    {
        $consultStatus = $consultStatus ? true : false;
        return StoreUserConsult::updateData(['consult_status' => (int)$consultStatus], ['id' => $consultId]);
    }

    /**
     * 门店服务平台-设置留资备注
     * @param $consultId
     * @param $remark
     * @return bool
     */
    public static function setConsultRemark($consultId, $remark)
    {
        return StoreUserConsult::updateData(['remark' => $remark], ['id' => $consultId]);
    }

    /**
     * 根据ids获取门店的基本信息
     * @param $store_ids
     * @return array
     */
    public static function GetStoreBasicByIds($store_ids, $field = ['id', 'name'])
    {
        return StoreBasic::getByIds($store_ids, $field);
    }

}